package com.learning.servlet3x.async;

import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * ClassName: CustomFilter
 * Description: Servlet3x新特性：支持异步的 Filter。
 * asyncSupported = true | dispatcherTypes = DispatcherType.ASYNC
 * Date:  2014/12/06 16:32 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@WebFilter(filterName = "asyncSupportedFilter", value = {"/async/*"},
        asyncSupported = true, dispatcherTypes = DispatcherType.ASYNC)
public class AsyncSupportedFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        System.out.println("监听到访问了：" + req.getRequestURL());
        chain.doFilter(request, response);

        // 在子线程中执行业务调用，并由其负责输出响应，主线程退出
        AsyncContext ctx = req.startAsync();
        //设置异步调用超时时长
        ctx.setTimeout(30 * 3000);
        //启动异步调用的线程
        ctx.start(new AsyncSupportedServlet.Executor(ctx));
    }

    @Override
    public void destroy() {

    }
}
